package com.example.fechat.room.user

import android.content.Context
import com.example.fechat.room.user.UserDatabase.Companion.getDatabase

object UserDBUtils {
    fun getAll(context: Context?): List<UserEntity> {
        val userDao = getDatabase(context!!)!!.userDao
        return userDao!!.queryAll()
    }

    fun getUserById(
        context: Context?,
        userId: String?
    ): UserEntity? {
        val userDao = getDatabase(context!!)!!.userDao
        return userDao!!.findByUserId(userId)
    }

    fun insertUser(context: Context?, user: UserEntity) {
        val userDao = getDatabase(context!!)!!.userDao
        val userEntity = userDao!!.findByUserId(user.userId)
        if (userEntity != null) {
            user._id = userEntity._id
            userDao.update(user)
        } else {
            userDao.insert(user)
        }
    }

    fun delete(context: Context?, user: UserEntity) {
        val userDao = getDatabase(context!!)!!.userDao
        val userEntity = userDao!!.findByUserId(user.userId)
        userDao.delete(userEntity)
    }

    fun deleteAll(context: Context?) {
        val all = getAll(context)
        val userDao = getDatabase(context!!)!!.userDao
        userDao!!.deleteAll(all)
    }

    fun insertAll(context: Context?, userEntities: List<UserEntity>) {
        deleteAll(context)
        for (i in userEntities.indices) {
            insertUser(context, userEntities[i])
        }
    }
}